export function parseQuery (query: string = location.search): Dictionary<string> {
  const res: Dictionary<string> = {}

  query = query.trim().replace(/^(\?|#|&)/, '')

  if (!query) {
    return res
  }

  query.split('&').forEach(param => {
    const parts = param.replace(/\+/g, ' ').split('=')
    const key = decodeURIComponent(parts.shift()!)
    const val = parts.length > 0
      ? decodeURIComponent(parts.join('='))
      : ''

    res[key] = val
    // if (res[key] === undefined) {
    //   res[key] = val
    // } else if (Array.isArray(res[key])) {
    //   res[key].push(val)
    // } else {
    //   res[key] = [res[key], val]
    // }
  })

  return res
}

export function stringifyQuery (obj: Dictionary<string>): string {
  if (!obj) {
    return ''
  }
  const queryArr: string[] = []
  Object.keys(obj).forEach(key => {
    const val = obj[key]
    if (val || val === '') {
      queryArr.push(`${key}=${encodeURIComponent(val)}`)
    }
  })
  return queryArr.join('&')
}

export const ua = window.navigator.userAgent
export const isAndroid = ua.indexOf('Android') > -1 || ua.indexOf('Adr') > -1
export const isiOS = !!ua.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)

export const browser = (() => {
  const isWechat = /micromessenger/i.test(ua)
  // eslint-disable-next-line no-useless-escape
  const isQQ = /QQ\/([\d\.]+)/.test(ua)
  return {
    isWechat,
    isQQ,
    isQZone: /Qzone\//.test(ua),
    isQQMBrowser: /MQQBrowser/i.test(ua) && !isWechat && !isQQ,
    isUCMBrowser: /UCBrowser/i.test(ua),
    // isBaiduMBrowser: /mobile.*baidubrowser/i.test(ua),
    // isSogouMBrowser: /SogouMobileBrowser/i.test(ua),
    // isBaiduApp: /baiduboxapp/i.test(ua),
  }
})()

export const isUndefined = (o: any) => typeof o === 'undefined'

export const setTitle = (title: string) => {
  document.title = title
  if (isiOS) {
    const iframe = document.createElement('iframe')
    iframe.src = '/favicon.ico'
    iframe.style.display = 'none'
    iframe.onload = () => {
      setTimeout(() => {
        iframe.remove()
      }, 10)
    }
    document.body.appendChild(iframe)
  }
}

const dangerousChars = {
  '&': '&amp;',
  '<': '&lt;',
  '>': '&gt;',
  "'": '&#39;',
  '"': '&quot;',
} as {
  [char: string]: string
}

export const replaceDangerousChar = (str: string) => {
  if (!str) {
    return ''
  } else {
    return str.replace(/[&<>'"]/, tag => (dangerousChars[tag] || tag))
  }
}

/**
 * 异步加载script
 *
 * @param {string} src
 * @param {string} scriptId 必须独特
 * @param {string} [onloadFnName] 链接内传callback时传，最好是独特的
 * @returns
 */
export const loadScript = (src: string, scriptId: string, onloadFnName?: string) => {
  return new Promise((resolve, reject) => {
    const scriptEl = document.getElementById(scriptId)
    if (scriptEl) {
      resolve()
      return
    }
    const script = document.createElement('script')
    script.charset = 'utf-8'
    script.id = scriptId
    if (onloadFnName) {
      (window as any)[onloadFnName] = resolve
    } else {
      script.onload = resolve
    }
    script.onerror = reject
    script.src = src
    document.body.appendChild(script)
  })
}

export const getHostFromUrl = (url: string) => {
  return url.split('/')[2]
}

export const imgToBase64 = (url: string) => {
  return new Promise<string>((resolve, reject) => {
    const img = new Image()
    img.crossOrigin = 'anonymous'
    img.src = url
    img.onload = () => {
      const canvas = document.createElement('canvas')
      canvas.width = img.width
      canvas.height = img.height

      const ctx = canvas.getContext('2d')
      ctx!.drawImage(img, 0, 0, canvas.width, canvas.height)
      const dataUrl = canvas.toDataURL()
      resolve(dataUrl)
    }
    img.onerror = reject
  })
}

type Dictionary<T> = { [key: string]: T }

export const rem2px = (rem: number) => {
  return rem * document.documentElement!.clientWidth / 10
}

// Type 筛选考试类型 0: 错题 1：模拟考试，2：历年真题,3.章节练习，4 每日一练
// ShowType： 0：所有题目；1：收藏的题目；2：做错的题目
export const testTitle: (ComplexTestTite|string)[] = [{
  1: '我的收藏',
  2: '我的错题',
}, '模拟考试', '历年真题', '章节练习', '每日一练']
interface ComplexTestTite {
  [k: number]: string
}

export const getTestTitle = (testQuery: TestQuery): string => {
  const { showAnswer, Type, ShowType } = testQuery
  console.log('getTestTitle', Type)
  /* eslint-disable eqeqeq */
  if (showAnswer && showAnswer == '1') {
    return '答案解析'
  }
  if (ShowType && ShowType != '0') {
    return testTitle[0][ShowType]
  }
  return testTitle[Type] as string
}

interface TestQuery {
  [key: string]: any
}
